<template>
    <div class="container">
        <v-container>
            <h4 class="mb-3" v-if="category == 'mortgage-tax'">企业税贷导入</h4>
            <h4 class="mb-3" v-if="category == 'mortgage-house'">房屋抵押贷导入</h4>
            <h4 class="mb-3" v-if="category == 'mortgage-car'">车辆抵押贷导入</h4>
            <h4 class="mb-3" v-if="category == 'credit-provident'">公积金信用贷导入</h4>
            <h4 class="mb-3" v-if="category == 'general'">银行综合贷款导入</h4>
        </v-container>

        <v-row>
            <v-col md="4" sm="12">
                <v-file-input  :rules="rules" accept=".xlsx"  v-model="file"  hide-details label="选择文件"></v-file-input>
            </v-col>
            <v-col class="d-inline-flex align-center">
                <v-btn class="mr-2" @click="uploadAndParse" color="primary" :loading="uploading || parsing" :disabled="saving">上传</v-btn>
                <v-btn class="mr-2" :href="`${route_prefix}/loan/template/${category}`" target="_blank" dark > 模版下载 </v-btn>
                <v-menu bottom offset-y>
                    <template v-slot:activator="{ on, attrs }">
                        <v-btn
                            dark
                            v-bind="attrs"
                            v-on="on"
                        >
                        其他类别
                        </v-btn>
                    </template>

                    <v-list>
                        <v-list-item :to="`/loan/import/general`" >
                            <v-list-item-title>银行综合贷款</v-list-item-title>
                        </v-list-item>
                        <v-list-item :to="`/loan/import/mortgage-tax`" >
                            <v-list-item-title>企业税贷</v-list-item-title>
                        </v-list-item>
                        <v-list-item :to="`/loan/import/mortgage-house`" >
                            <v-list-item-title>房屋抵押贷</v-list-item-title>
                        </v-list-item>
                        <v-list-item :to="`/loan/import/mortgage-car`" >
                            <v-list-item-title>车辆抵押贷</v-list-item-title>
                        </v-list-item>
                        <v-list-item :to="`/loan/import/credit-provident`" >
                            <v-list-item-title>公积金信用贷</v-list-item-title>
                        </v-list-item>
                    </v-list>
                </v-menu>
            </v-col>
        </v-row>

        <v-data-table
            v-if="previewItem.length > 0"
            item-key="id"
            :headers="previewHeader"
            :items="previewItem"
            class="mt-8"
            no-data-text="没有数据..."
            hide-default-footer
        >

            <template v-slot:top>
                <v-divider></v-divider>
                <v-toolbar  flat >
                    <v-toolbar-title>数据预览 {{previewItem.length}} 条， 共 {{previewTotal}} 条数据 </v-toolbar-title>
                    <v-spacer></v-spacer>
                    <v-btn  @click="save" :loading="saving" color="primary" :disabled="progressing || server_file.length == 0 || progressCnt > 0">导入</v-btn>
                </v-toolbar>
                <v-progress-linear :color="progressColor" height="25"  :buffer-value="progress" v-if="progressTotal > 0"  class="mb-2">
                    <strong>总数: {{progressTotal}}</strong>
                    <strong class="ml-1">成功: {{progressCnt}}</strong>
                    <strong v-if="progressFailCnt > 0 "  class="ml-1">失败: {{progressFailCnt}}</strong>
                    <strong v-if="progressDuplicateCnt > 0 "  class="ml-1">重复: {{progressDuplicateCnt}}</strong>
                </v-progress-linear>
                <v-divider v-else></v-divider>
            </template>
        </v-data-table>

        <v-row v-if="server_file.length> 0 && !parsing && previewItem.length == 0">
            <v-divider ></v-divider>
            <v-col cols="12" > <span class="ml-4">没有数据...</span></v-col>
        </v-row>
   
    </div>
</template>

<script>
    import axios from "axios";

    export default {
        data: () => ({
          category : '',
          route_prefix: ROUTE_PREFIX,
          file: null,
          server_file: '',
          rules: [
            value => !value || value.size < 5000000 || '文件不能超过5MB',
          ],
          uploading: false,
          parsing: false,
          saving: false,
          previewTotal: 0,
          previewHeader: [],
          previewItem: [],
          progressing: false,
          progress: 0,
          progressTotal: 0,
          progressCnt: 0,
          progressFailCnt: 0,
          progressDuplicateCnt: 0,
          progressKey: '',
        }),

        computed: {
            progressColor() {
               if (this.progressFailCnt > 0) return 'red';

               if (this.progressDuplicateCnt > 0) return 'orange';

               return 'green';
            }
        },


        created() {
            this.category = this.$route.params.category;
        },

        beforeRouteUpdate(to, from, next) {
            this.category = to.params.category;
            this.reset();
            next();
        },

        methods: {
            reset() {
                this.server_file = '';
                this.headers = [];
                this.previewItem = [];
                this.progress = 0;
                this.progressTotal = 0;
                this.progressCnt = 0;
            },
            uploadAndParse() {

                let form= new FormData();
                form.append('file', this.file)

                this.uploading = true;
                this.reset();
                const that = this;
                axios.post('/import/upload', form, { headers: {'Content-Type': 'multipart/form-data' } } )
                    .then((response) => {
                        if (response.data.code === 0) {
                         this.server_file = response.data.data;
                         this.parse();
                        }
                    })
                    .catch(function () {})
                    .then(function () {
                        that.uploading = false;
                    });
            },

            parse() {
                  this.parsing = true;
                  const that = this;
                  axios.post('/import/parse', {file: this.server_file})
                  .then((response) => {
                        if (response.data.code === 0) {
                            this.previewHeader = response.data.data.headers.map(v => new Object({ text: v, value: v }));
                            this.previewItem = response.data.data.items;
                            this.previewTotal = response.data.data.total;
                        }  else {
                            this.$toast.open({
                                message: response.data.msg,
                                type: 'error',
                                position: 'top-right',
                            });
                        }
                    })
                    .catch(function () {})
                    .then(function () {
                        that.parsing = false;
                    });
            },

            save() {
                  this.saving = true;
                  const that = this;
                  axios.post(`/import/save/${this.category}`, {file: this.server_file})
                  .then((response) => {
                        if (response.data.code === 0) {
                           this.progressKey = response.data.data.key;
                           this.loadProgress();
                        }  else {
                            this.$toast.open({
                                message: response.data.msg,
                                type: 'error',
                                position: 'top-right',
                            });
                        }
                    })
                    .catch(function () {})
                    .then(function () {
                        that.saving = false;
                    });
            },

            loadProgress() {
                  this.progressing = true;
                  const that = this;
                  axios.post(`/import/progress`, {key: this.progressKey})
                  .then((response) => {
                        if (response.data.code === 0) {
                            if (response.data.data.progress == 0 || response.data.data.progress < response.data.data.total) {
                                setTimeout(() => that.loadProgress(), 2000);
                            }
                         
                           if (response.data.data.total > 0) {
                                this.progress = (response.data.data.progress * 100) / response.data.data.total;
                           } else {
                                this.progress = 0;
                           } 

                           if ( response.data.data.progress > 0 && response.data.data.progress == response.data.data.total) {
                              this.progressing = false;
                           }
                           this.progressTotal = response.data.data.total;
                           this.progressCnt = response.data.data.success;
                           this.progressFailCnt = response.data.data.fail;
                           this.progressDuplicateCnt = response.data.data.duplicate;
                        }  else {
                            this.$toast.open({
                                message: response.data.msg,
                                type: 'error',
                                position: 'top-right',
                            });
                        }
                    }).catch(function () {
                         this.progressing = false;
                    })
                    .then(function () {
                        
                  });
            }
        }
    }
</script>
